package cn.com.libertymutual.sp.biz;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;

import cn.com.libertymutual.core.redis.util.RedisUtils;
import cn.com.libertymutual.core.util.Constants;
import cn.com.libertymutual.core.web.ServiceResult;
import cn.com.libertymutual.sp.bean.TbSpSaleLog;
import cn.com.libertymutual.sp.bean.TbSpShare;
import cn.com.libertymutual.sp.bean.TbSpUser;
import cn.com.libertymutual.sp.bean.TbSysHotarea;
import cn.com.libertymutual.sp.bean.TbWebRequestLog;
import cn.com.libertymutual.sp.dao.ShareDao;
import cn.com.libertymutual.sp.dao.SpSaleLogDao;
import cn.com.libertymutual.sp.dao.TbSysHotareaDao;
import cn.com.libertymutual.sp.dao.UserDao;
import cn.com.libertymutual.sp.dto.PlanDto;
import cn.com.libertymutual.sp.dto.queryplans.QueryPlansRequestDTO;
import cn.com.libertymutual.sp.dto.queryplans.QueryPlansResponseDTO;
import cn.com.libertymutual.sp.dto.savePlan.PropsalSaveRequestDto;
import cn.com.libertymutual.sp.service.api.AdConfigService;
import cn.com.libertymutual.sp.service.api.ClauseService;
import cn.com.libertymutual.sp.service.api.CodeRelateService;
import cn.com.libertymutual.sp.service.api.ProductService;
import cn.com.libertymutual.sp.service.api.ServiceMenuService;
import cn.com.libertymutual.sp.service.api.TbWebRequestLogService;

@Component
public class ProductBiz {

	private Logger log = LoggerFactory.getLogger(getClass());

	// 注入原子性业务逻辑
	@Resource
	private ProductService productService;
	@Resource
	private ServiceMenuService serviceMenuService;
	@Resource
	private AdConfigService adConfigService;
	@Resource
	private TbWebRequestLogService tbWebRequestLogService;
	@Resource
	private CodeRelateService codeRelateService;
	@Resource
	private ClauseService clauseService;
	@Resource
	private IdentifierMarkBiz identifierMarkBiz;
	@Resource
	private RedisUtils redis;
	@Autowired
	private ShareDao shareDao;
	@Autowired
	private UserDao userDao;
	@Autowired
	private TbSysHotareaDao tbSysHotareaDao;
	@Autowired
	private SpSaleLogDao spSaleLogDao;

	/**Remarks: 前端三个接口合并<br>
	 * Version：1.0<br>
	 * Author：AoYi<br>
	 * DateTime：2017年11月9日下午11:51:31<br>
	 * Project：liberty_sale_plat<br>
	 * @param request
	 * @param response
	 * @param region
	 * @param type
	 * @param sorttype
	 * @param pageNumber
	 * @param pageSize
	 * @param pointX
	 * @param pointY
	 * @param userId
	 * @return
	 * @throws Exception
	 */
	public ServiceResult productMenuAd(HttpServletRequest request, HttpServletResponse response, String region, String type, String sorttype,
			Integer pageNumber, Integer pageSize, String pointX, String pointY, String userId, String uuid, String userCode, boolean isShop,
			String markUuid) throws Exception {
		ServiceResult sr = new ServiceResult(Constants.SYS_ERROR_MSG, ServiceResult.STATE_EXCEPTION);
		try {
			// Md5PwdEncoder md5PwdEncoder = new Md5PwdEncoder();
			// String salt = md5PwdEncoder.encodePassword("LCB", "HENGHUA");
			// Md5PwdEncoder md5PwdEncoder = new Md5PwdEncoder();
			// // 加密密码
			// String password = md5PwdEncoder.encodePassword("BS00000016");
			// System.out.println(password);
			String ip = request.getHeader("x-forwarded-for");
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("proxy-client-ip");
			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("wl-proxy-client-ip");
			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getRemoteAddr();
			}
			TbWebRequestLog tequestLog = new TbWebRequestLog();
			tequestLog.setLongitude(pointX);
			tequestLog.setOperationTime(new Date());
			tequestLog.setUserId(userId);
			tequestLog.setRemark(markUuid);
			tequestLog.setRequestData("");
			tequestLog.setResponseData("");
			tequestLog.setUrl("");
			tequestLog.setLatitude(pointY);
			tequestLog.setIP(ip);
			tequestLog.setRequestTime(new Date());
			tequestLog.setCityId(region);
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("product", productService.productFindAll(region, type, pageNumber, pageSize, sorttype).getResult());
			// map.put("menu", serviceMenuService.menuList(sorttype).getResult());
			map.put("advert", adConfigService.advertList(sorttype).getResult());
			// map.put("riskCode", productService.riskCodeDistinct());
//			Object obj = productService.findAreaInfoByName(region).getResult();
			Object obj = productService.findAreaInfoByName("恒华保险代理有限公司").getResult();
			map.put("version", "18.04.28.1500");
			map.put("hotarea", obj);
			// map.put("initData",
			// codeRelateService.getSaleInitData("SaleInitData").getResult());
			map.put("initUrlData", codeRelateService.findSaleInitUrlData("SaleInitData").getResult());
			map.put("addre", "");
			map.put("time", new Date().getTime());
			if (StringUtils.isNotBlank(uuid)) {
				List<TbSpShare> tbSpList = shareDao.findByShareId(uuid);
				if (CollectionUtils.isNotEmpty(tbSpList)) {
					TbSpShare tbSp = tbSpList.get(0);
					TbSpUser resUser = new TbSpUser();
					TbSpUser shareUser = userDao.findByUserCode(tbSp.getUserCode());
					resUser.setUserCode(tbSp.getUserCode());
					if (tbSp.getSharinChain() != null) {
						tbSp.setSharinChain(tbSp.getSharinChain() + 1);
					} else {
						tbSp.setSharinChain(1);
					}
					tbSp.setState(TbSpShare.SHARE_TYPE_VISIT);
					if (shareUser != null) {
						// if(tbSp.getSharinChain()!=null) {
						// tbSp.setSharinChain(tbSp.getSharinChain() + 1);
						// }else {
						// tbSp.setSharinChain(1);
						// }
						// tbSp.setState(TbSpShare.SHARE_TYPE_VISIT);
						resUser.setIdNumber(shareUser.getIdNumber());
						resUser.setStoreFlag(shareUser.getStoreFlag());
						resUser.setUserType(shareUser.getUserType());
						resUser.setAreaCode(shareUser.getAreaCode());
						// resUser.setComCode(shareUser.getComCode());
						// 记录哪个用户点击过此链接
						// if (StringUtils.isNotBlank(tbSp.getUserCodeChain())) {
						// if (tbSp.getUserCodeChain().indexOf(userCode) == -1 &&
						// tbSp.getUserCodeChain().length() < 500) {
						// tbSp.setUserCodeChain(tbSp.getUserCodeChain() + " " + userCode);
						// }
						// } else {
						// tbSp.setUserCodeChain(userCode);
						// }
						resUser.setStoreFlag(shareUser.getStoreFlag());
						if (shareUser != null && StringUtils.isNotBlank(shareUser.getAgrementNo())) {
							resUser.setAgrementNo(shareUser.getAgrementNo());
							resUser.setSaleCode(shareUser.getSaleCode());
							resUser.setSaleName(shareUser.getSaleName());
							resUser.setUserCode(tbSp.getUserCode());
							resUser.setChannelName(shareUser.getChannelName());

							tbSp.setAgrementNo(shareUser.getAgrementNo());
							tbSp.setSaleCode(shareUser.getSaleCode());
							tbSp.setSaleName(shareUser.getSaleCode());
							tbSp.setChannelName(shareUser.getChannelName());
						} else if (shareUser != null && StringUtils.isEmpty(shareUser.getAgrementNo())
								&& StringUtils.isNotBlank(shareUser.getAreaCode())) {
							TbSysHotarea hotArea = tbSysHotareaDao.findByAreaCode(shareUser.getAreaCode());

							resUser.setAgrementNo(hotArea.getAgreementNo());
							resUser.setSaleCode(hotArea.getSaleCode());
							resUser.setSaleName(hotArea.getSaleName());
							resUser.setUserCode(tbSp.getUserCode());
							resUser.setChannelName(hotArea.getBranchName());

							tbSp.setAgrementNo(hotArea.getAgreementNo());
							tbSp.setSaleCode(hotArea.getSaleCode());
							tbSp.setChannelName(hotArea.getBranchName());
						}
						// shareDao.save(tbSp);
						// resUser.setUserCode(userCode);
						// resUser.setAgrementNo(tbSp.getAgrementNo());
						// resUser.setPopularity(shareUser.getPopularity());
						// resUser.setSaleCode(tbSp.getSaleCode());
						// resUser.setSaleName(tbSp.getSaleName());
						// resUser.setUserCode(tbSp.getUserCode());
						// resUser.setChannelName(tbSp.getChannelName());
						// resUser.setTypeState(shareUser.getTypeState());
						// resUser.setStoreFlag(shareUser.getStoreFlag());
						// //访问人气
						// if(isShop) {
						// Object ipIsAcc = redis.get(tbSp.getUserCode()+ip);
						// if(ipIsAcc == null) {
						// redis.setWithExpireTime(tbSp.getUserCode()+ip,true,3600*24);
						// Integer popularity = shareUser.getPopularity();
						// popularity++;
						// shareUser.setPopularity(popularity);
						// userDao.save(shareUser);
						// }
						// resUser.setVolume(orderDao.findUserCount(tbSp.getUserCode()));
						// }
					} else {
						resUser.setAgrementNo(tbSp.getAgrementNo());
						resUser.setSaleCode(tbSp.getSaleCode());
						resUser.setSaleName(tbSp.getSaleName());
						resUser.setUserCode(tbSp.getUserCode());
						resUser.setChannelName(tbSp.getChannelName());
					}
					shareDao.save(tbSp);
					map.put("agr", resUser);
				} else {
					map.put("agr", false);
				}
			} else {
				map.put("agr", false);
			}
			sr.setSuccess();
			sr.setResult(map);
			// 设置请求编码
			// sr.setResCode(identifierMarkBiz.getIdentifier(request));//已改存headers里
			// response.setHeader(Constants.IDENTIFICATION_MARK,
			// identifierMarkBiz.getIdentifier(request));
			TbSysHotarea hotarea = (TbSysHotarea) obj;
			redis.setString(Constants.BRANCH_OFFICE_CODE, hotarea.getBranchCode());
			tequestLog.setResponseTime(new Date());
			tbWebRequestLogService.saveWebRequestLog(tequestLog);
		} catch (Exception e) {
			e.printStackTrace();
			log.warn("异常:{}", e.toString());
		}
		return sr;
	}

	/**Remarks: 按不同分类查询产品<br>
	 * Version：1.0<br>
	 * Author：AoYi<br>
	 * DateTime：2017年11月9日下午11:51:40<br>
	 * Project：liberty_sale_plat<br>
	 * @param request
	 * @param response
	 * @param identCode
	 * @param region
	 * @param type
	 * @param sorttype
	 * @param pageNumber
	 * @param pageSize
	 * @return
	 * @throws Exception
	 */
	public ServiceResult productList(HttpServletRequest request, HttpServletResponse response, String identCode, String region, String type,
			String sorttype, Integer pageNumber, Integer pageSize) throws Exception {
		ServiceResult sr = new ServiceResult(Constants.SYS_ERROR_MSG, ServiceResult.STATE_EXCEPTION);
		try {
			sr = productService.productFindAll(region, type, pageNumber, pageSize, sorttype);
		} catch (Exception e) {
			log.warn("按不同分类查询产品异常:" + e.toString());
		}
		return sr;
	}

	public ServiceResult getInitUrl(HttpServletRequest request, HttpServletResponse response, String identCode) throws Exception {
		ServiceResult sr = new ServiceResult(Constants.SYS_ERROR_MSG, ServiceResult.STATE_EXCEPTION);
		try {
			sr = codeRelateService.findSaleInitUrlData("SaleInitDataWe");
		} catch (Exception e) {
			log.warn("异常:" + e.toString());
		}
		return sr;
	}

	/**Remarks: 根据产品ID获取套餐计划<br>
	 * Version：1.0<br>
	 * Author：AoYi<br>
	 * DateTime：2017年11月9日下午11:51:15<br>
	 * Project：liberty_sale_plat<br>
	 * @param request
	 * @param response
	 * @param identCode
	 * @param productId
	 * @param age
	 * @param deadLine
	 * @return
	 * @throws Exception
	 */
	public ServiceResult queryPlans(String planId, String age,
			String deadLine,String seat) throws Exception {
		ServiceResult sr = new ServiceResult(Constants.SYS_ERROR_MSG, ServiceResult.STATE_EXCEPTION);
		
		PlanDto planDto  = new PlanDto();
		planDto.setAge(age);
		planDto.setDay(deadLine);
		planDto.setGpaPlanCode(planId);
		planDto.setSeat(seat);
		planDto.setCarType("1");
		planDto.setCarNature("1");
		
		try {
			
			QueryPlansResponseDTO plansRs = productService.queryPlansByPlanCode(planDto);
			if(plansRs.getStatus()){
				sr.setSuccess();
				sr.setResult(plansRs.getPlanLists());
			}else{
				sr.setFail();
				sr.setResult(plansRs.getResultMessage());
			}
		} catch (Exception e) {
			log.warn("异常:" + e.toString());
		}
		return sr;
	}

	/**Remarks: 根据计划ID，年龄，期限查询计划套餐<br>
	 * Version：1.0<br>
	 * Author：AoYi<br>
	 * DateTime：2017年11月9日下午11:52:18<br>
	 * Project：liberty_sale_plat<br>
	 * @param request
	 * @param response
	 * @param identCode
	 * @param planId
	 * @param age
	 * @param deadLine
	 * @return
	 * @throws Exception
	 */
	public ServiceResult queryPlan(HttpServletRequest request, HttpServletResponse response, String identCode, String planId, Integer age,
			Integer deadLine) throws Exception {
		ServiceResult sr = new ServiceResult(Constants.SYS_ERROR_MSG, ServiceResult.STATE_EXCEPTION);
		try {
			// productId="0";
			// age=23;
			// deadLine=30;
			sr = productService.queryPlan(planId, age, deadLine);
		} catch (Exception e) {
			TbSpSaleLog saleLog = new TbSpSaleLog();
			saleLog.setRequestTime(new Date());
			if (age == null || deadLine == null) {
				saleLog.setRequestData("identCode:" + identCode + "-planId:" + planId);
			} else {
				saleLog.setRequestData("identCode:" + identCode + "-planId:" + planId + "-age:" + age.toString() + "-deadLine" + deadLine.toString());
			}
			saleLog.setOperation("请求计划");
			saleLog.setResponseData(e.toString());
			saleLog.setMark("请求计划出错");
			spSaleLogDao.save(saleLog);
			log.warn("异常:" + e.toString());
		}
		return sr;
	}

	/**Remarks: 根据产品ID查询计划套餐<br>
	 * Version：1.0<br>
	 * Author：AoYi<br>
	 * DateTime：2017年11月9日下午11:53:33<br>
	 * Project：liberty_sale_plat<br>
	 * @param request
	 * @param response
	 * @param identCode
	 * @param productId
	 * @return
	 * @throws Exception
	 */
	public ServiceResult querySalePlan(HttpServletRequest request, HttpServletResponse response, String identCode, String productId, String userCode)
			throws Exception {
		return productService.querySalePlan(productId, userCode);
	}

	public ServiceResult savePlan(HttpServletRequest request, HttpServletResponse response, String identCode,
			@RequestBody PropsalSaveRequestDto requestDto) throws Exception {
		ServiceResult sr = new ServiceResult(Constants.SYS_ERROR_MSG, ServiceResult.STATE_EXCEPTION);
		try {
			sr = productService.savePlan(requestDto);
		} catch (Exception e) {
			sr.setFail();
			sr.setResult(e);
			log.warn("异常:{}", e.getMessage());
			log.error("投保失败", e);
		}
		return sr;
	}

	public ServiceResult queryClause(HttpServletRequest request, HttpServletResponse response, String identCode, String planId, String clauseTitle)
			throws Exception {
		ServiceResult sr = new ServiceResult(Constants.SYS_ERROR_MSG, ServiceResult.STATE_EXCEPTION);
		try {
			sr = clauseService.queryClause(planId, clauseTitle);
		} catch (Exception e) {
			log.warn("异常:" + e.toString());
		}
		return sr;
	}

	public ServiceResult queryClauseTitle(String planId) throws Exception {
		ServiceResult sr = new ServiceResult(Constants.SYS_ERROR_MSG, ServiceResult.STATE_EXCEPTION);
		sr = clauseService.queryClauseTitle(planId);
		return sr;
	}
}
